package com.hzit.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.cloud.netflix.ribbon.RibbonHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class ResponseFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("--------执行POST过滤器---------------");

//        Responsecon

        Object zuulResponse = RequestContext.getCurrentContext().get("zuulResponse");
        String text = null;
        System.out.println("--------zuulResponse---------------" + zuulResponse);

        if (zuulResponse != null) {
            RibbonHttpResponse resp = (RibbonHttpResponse) zuulResponse;
            InputStream inputStream = null;
            try {
                 inputStream = resp.getBody();
                System.out.println("-----inputStream = " + inputStream);
                byte b [] = readStream(inputStream);
                  text = new String(b,"utf-8");
                  System.out.println("-----text = " + text);



            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
               if (inputStream!=null){
                   try {
                       inputStream.close();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
            }


            resp.close();
            RequestContext.getCurrentContext().setResponseBody(text);
//            resp.close();
//            RequestContext.getCurrentContext().setResponseBody(body);
        }


        return null;
    }


    /**
     * 读取流
     *
     * @param inStream
     * @return 字节数组
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }
}
